import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_baichuan/models/user_model.dart';
import 'package:flutter_baichuan/models/init_model.dart';
import 'package:flutter_baichuan/models/login_model.dart';
import 'package:flutter_baichuan/models/access_token_model.dart';
import 'package:flutter_baichuan/alibc_const_key.dart';

class FlutterBaichuan {
  static const MethodChannel _channel = MethodChannel('flutter_baichuan');

  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  ///初始化
  ///version:当前app版本
  ///appName:当前app名称
  ///result:{
  ///   errorCode,     //0为初始化成功，其他为失败
  ///   errorMessage,  //message
  ///}
  static Future<InitModel> initAlibc({String? version, String? appName}) async {
    Map result = await _channel
        .invokeMethod("initAlibc", {"version": version, "appName": appName});
    return InitModel(result[AlibcConstKey.errorCode],
        result[AlibcConstKey.errorMessage], result['utdid']);
  }

  ///
  /// @description: 登录淘宝
  ///
  /// @return: 成功则返回的data为用户信息，失败则没有data
  ///
  static Future<LoginModel> loginTaoBao() async {
    Map result = await _channel.invokeMethod("loginTaoBao");
    final loginModel = LoginModel.fromMap(result);
    return loginModel;
  }

  /// 获取token
  static Future<AccessTokenModel> getAccessToken(
      {required String appKey, required String appName}) async {
    Map result = await _channel
        .invokeMethod('getAccessToken', {'appKey': appKey, 'appName': appName});
    final data = AccessTokenModel.fromMap(result);
    return data;
  }

  static Future<String> getUtdid() async {
    String result = await _channel.invokeMethod("getUtdid");
    return result;
  }

  static void loignOut() {
    _channel.invokeMethod('loginOut');
  }

  static Future<bool> isLogin() async {
    final result = await _channel.invokeMethod('isLogin');
    var state = false;
    if (result is bool) {
      state = result;
    }
    return state;
  }

  /// 打开商品
  ///
  /// [id] 商品id
  /// [pid] 淘客ID
  /// [relationId] 渠道id
  static void openByCode({
    required String id,
    required String pid,
    required String relationId,
  }) {
    _channel.invokeMethod(
        'openByCode', {"id": id, 'pid': pid, 'relationId': relationId});
  }

  static void openByUrl({
    required String url,
    required String id,
    required String pid,
    required String relationId,
  }) {
    _channel.invokeMethod('openByUrl',
        {"url": url, "id": id, 'pid': pid, 'relationId': relationId});
  }
}
